package com.netty.common.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

/**
 * Netty自带了几种拆包器：
 * 固定长度的拆包器 FixedLengthFrameDecoder、行拆包器 LineBasedFrameDecoder、
 * 分隔符拆包器 DelimiterBasedFrameDecoder、长度域拆包器LengthFieldBasedFrameDecoder。
 * <p>
 * 长度域拆包器 LengthFieldBasedFrameDecoder。
 */
public class ImFrameDecoder extends LengthFieldBasedFrameDecoder {
    private static final int LENGTH_FIELD_OFFSET = 7;
    private static final int LENGTH_FIELD_LENGTH = 4;

    public ImFrameDecoder() {
        super(Integer.MAX_VALUE, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf inByteBuf) throws Exception {
        if (inByteBuf.getInt(inByteBuf.readerIndex()) != PacketCodec.MAGIC_NUMBER) {
            ctx.channel().close();
            return null;
        }

        return super.decode(ctx, inByteBuf);
    }
}
